package com.sc.demo2.common.config;



import com.sc.common.interceptors.ContextHandlerDefaultInterceptor;
import com.sc.common.interceptors.CrosInterceptor;
import com.sc.common.util.MyMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import java.util.List;


/**
 * Created by wust on 2019/2/18.
 */
@SpringBootConfiguration
public class WebMvcConfiguration extends WebMvcConfigurationSupport {
    @Autowired
    private Environment environment;

    @Autowired
    private MyMessageConverter myMessageConverter;

    @Bean
    public ContextHandlerDefaultInterceptor contextHandlerDefaultInterceptor() {
        return new ContextHandlerDefaultInterceptor();
    }

    @Bean
    public CrosInterceptor crosInterceptor(){
        return new CrosInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(contextHandlerDefaultInterceptor()); // 业务上下文配置
        registry.addInterceptor(crosInterceptor()).addPathPatterns("/**/**"); // 跨域配置
    }

    @Override
    protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        myMessageConverter.configureMessageConverters(converters);
    }


    /**
     * 跨域支持
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("*")
                .maxAge(3600)
                .allowedHeaders("X-Requested-With", "Content-Type","token");
    }

    /**
     * 添加静态资源--过滤swagger-api (开源的在线API文档)
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/js/**").addResourceLocations("classpath:/js/");
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");

    }
}
